package db

import (
	"TD-UI/internal/logic/link"
	"TD-UI/internal/model"
	"TD-UI/internal/service"
	"context"
	"fmt"
	"sync"
)

func init() {
	service.RegisterDb(New())
}

type sDb struct {
}

func New() service.IDb {
	return &sDb{}
}

var lock sync.Mutex

func (s *sDb) CreateDb(ctx context.Context, req model.DbReq) (res model.DbRes, err error) {
	lock.Lock()
	defer lock.Unlock()
	taos, err := link.OpenTasos(req.LinkId, req.DbName, true)
	if err != nil {
		panic(err)
	}
	defer taos.Close()
	var sql = fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", req.DbName)
	_, err = taos.Exec(sql)
	if err != nil {
		panic(err)
	}
	return

}

type Ddl struct {
	Database       string
	CreateDatabase string
}

func (s *sDb) Dbddl(ctx context.Context, req model.DbDdlReq) (res model.DbRes, err error) {
	//TODO implement me
	taos, err := link.OpenTasos(req.LinkId, req.DbName, true)
	if err != nil {
		panic(err)
	}
	defer taos.Close()
	var sql = fmt.Sprintf("SHOW CREATE DATABASE %s", req.DbName)
	result, err := taos.Query(sql)
	if err != nil {
		panic(err)
	}
	defer result.Close()
	var createSql string
	for result.Next() {
		ddl := *new(Ddl)
		_ = result.Scan(&ddl.Database, &ddl.CreateDatabase)
		createSql = ddl.CreateDatabase
	}
	res.Result = createSql
	return
}

func (s *sDb) DbDel(ctx context.Context, req model.DbDelReq) (res model.DbRes, err error) {
	//TODO implement me
	taos, err := link.OpenTasos(req.LinkId, req.DbName, true)
	if err != nil {
		panic(err)
	}
	defer taos.Close()
	var sql = fmt.Sprintf("DROP DATABASE IF EXISTS %s", req.DbName)
	_, err = taos.Exec(sql)
	if err != nil {
		panic(err)
	}
	return
}
